﻿using System;
using System.Text;

namespace CommonFramework.Log
{
    /// <summary>
    /// 继承该类实现日志消息的回调处理
    /// </summary>
    public abstract class LogMessageHandler:IDisposable
    {
        public LogMessageHandler()
        {
            LogUtil.ListenLogMessage(NotifyLogMessage, isAdd:true);
        }
        public void Dispose()
        {
            LogUtil.ListenLogMessage(NotifyLogMessage, isAdd:false);
        } 
        public virtual bool NeedBackTrace()=> false;

        public void NotifyLogMessage(LogMessage msg, bool isBackTrace)
        {
            if (!isBackTrace || NeedBackTrace())
                OnLogMessage(msg,isBackTrace);
        }
        protected abstract void OnLogMessage(LogMessage message,bool isBackTrace);
    }

    internal class DefaultLogMessageHandler : LogMessageHandler
    {
        protected override void OnLogMessage(LogMessage message, bool isBackTrace)
        {
            var modifier = message.GetModifier();
            //带上时间消息头
            modifier.AppendHead(LogUtil.TimeHead());
        }
    }

    /// <summary>
    /// 将日志消息输出到控制台,根据日志消息的不同级别使用不同的字体颜色
    /// </summary>
    public class ConsoleLogMessageHandler : LogMessageHandler
    {
        protected override void OnLogMessage(LogMessage message, bool isBackTrace)
        {
            //每条日志消息最后带上一个换行符,防止和下一条消息粘在同一行
            var modifier = message.GetModifier();
            string msg = message.GetContent();
            if (!msg.EndsWith("\n"))
            {
                modifier.AppendContent("\n");
            }

            Console.ForegroundColor = GetColorByLogSeverity(message.Severity);
            Console.Write(message.GetContent());
            Console.ResetColor();
        }

        private ConsoleColor GetColorByLogSeverity(LogSeverity severity)
        {
            switch (severity)
            {
                case LogSeverity.Error:   return ConsoleColor.Red;
                case LogSeverity.Warning: return ConsoleColor.Yellow;
                case LogSeverity.Info:    return ConsoleColor.Green;
                case LogSeverity.Verbose: return ConsoleColor.DarkGray;
                default:
                    return ConsoleColor.White;
            }
        }
    }
}